package com.yxq.mdt.app.modules.login.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.orhanobut.hawk.Hawk;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.modules.login.bean.UserBean;
import com.yxq.mdt.app.modules.login.model.LoginModel;
import com.yxq.mdt.app.modules.login.presenter.ILoginContract;
import com.yxq.mdt.app.modules.login.presenter.LoginPresenter;
import com.yxq.mdt.app.modules.main.ui.MainActivity;
import com.yxq.mdt.app.modules.personal.bean.MainPersonTokenBean;
import com.yxq.mdt.app.modules.personal.bean.MainPersonalImNumber;
import com.yxq.mdt.app.net.API;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.modules.webview.ui.MiWebViewActivity;
import com.yxq.mdt.app.utils.StringUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author L
 * @time
 * @describe 用户注册
 */
public class RegisterActivity extends BaseActivity<LoginPresenter> implements ILoginContract.View {

    @BindView(R.id.login_et_account)
    EditText accountEditText;
    @BindView(R.id.login_et_pwd)
    EditText passwordEditText;
    @BindView(R.id.login_et_re_pwd)
    EditText rePasswordEditText;
    @BindView(R.id.login_et_code)
    EditText codeEditText;
    @BindView(R.id.login_et_invite_code)
    EditText inviteEditText;
    @BindView(R.id.login_tv_code)
    TextView codeTextView;
    CountDownTimer countDownTimer;
    @BindView(R.id.tv_user)
    TextView tvUser;
    @BindView(R.id.tv_privacy)
    TextView tvPrivacy;
    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    Handler handler = new Handler();

    @Override
    public int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        mPresenter = new LoginPresenter(this, new LoginModel());
    }

    @Override
    protected void back() {
        Intent intent = new Intent(mActivity, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(mActivity, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

    }

    @OnClick({R.id.login_btn_login, R.id.login_tv_code, R.id.login_btn_register, R.id.tv_user, R.id.tv_privacy})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn_login:
                //注册
                register();
                break;
            case R.id.login_tv_code:
                //验证码
                verifyCode();
                break;
            case R.id.login_btn_register:
                //返回
                Intent intent = new Intent(mActivity, LoginActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.tv_user://用户协议
                intent = new Intent(mActivity, MiWebViewActivity.class);
                intent.putExtra("url", API.USER_AGREEMENT);
                intent.putExtra("title", "用户协议");
                startActivity(intent);
                break;
            case R.id.tv_privacy://隐私协议
                intent = new Intent(mActivity, MiWebViewActivity.class);
                intent.putExtra("url", API.PRIVACY_POLICY);
                intent.putExtra("title", "隐私协议");
                startActivity(intent);
                break;
        }
    }

    private void verifyCode() {
        if (accountEditText.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入手机号码");
            return;
        }
        if (!StringUtils.isMobileExact(accountEditText.getText().toString())) {
            ToastUtils.showShort("请输入合法的手机号码");
            return;
        }
        showLoadingDialog();
        mPresenter.verifyCode(accountEditText.getText().toString(), 1);
    }

    private void register() {
        if (accountEditText.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入手机号码");
            return;
        }

        if (!StringUtils.isMobileExact(accountEditText.getText().toString())) {
            ToastUtils.showShort("请输入合法的手机号码");
            return;
        }
        if (passwordEditText.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入密码");
            return;
        }
        if (rePasswordEditText.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入确认密码");
            return;
        }
        if (codeEditText.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入验证码");
            return;
        }
        if (!rePasswordEditText.getText().toString().equals(passwordEditText.getText().toString())) {
            ToastUtils.showShort("两次输入的密码不一致");
            return;
        }
        showLoadingDialog(false);
        String invited = "0";
        if (inviteEditText.getText().toString().length() > 0) {
            invited = inviteEditText.getText().toString();
        }
        mPresenter.register(accountEditText.getText().toString(), passwordEditText.getText().toString(), rePasswordEditText.getText().toString(), 2, codeEditText.getText().toString(), invited);
    }

    @Override
    public void onLoginSuccess(UserBean userBean) {
        if (userBean != null) {
            if (userBean.getBlacklist() == 1) {
                hideLoadingDialog();
                //黑名单 不允许登录
                ToastUtils.showShort("您已被禁止登录！");
                return;
            }
            //判断是否需要绑定手机号
            if (StringUtils.isEmpty(userBean.getBinding()) || "null".equals(userBean.getBinding())) {
                hideLoadingDialog();
                //跳转绑定手机号
                startBindPhoneActivity(userBean);
            } else {
                //创建JAVA平台Token
                createToken(userBean);
            }
        } else {
            ToastUtils.showShort("登录失败");
        }
    }

    /**
     * 创建java Token
     */
    private void createToken(UserBean userBean) {
        mPresenter.getTokenData(String.valueOf(userBean.getUserId()), new ApiModel.CommonCallback<MainPersonTokenBean>() {
            @Override
            public void onSuccess(MainPersonTokenBean mainPersonTokenBean) {
                Hawk.delete(SPKey.SP_KEY_USER_INFO_TOKEN);
                Hawk.put(SPKey.SP_KEY_USER_INFO_TOKEN, mainPersonTokenBean);
                //获取环信账号
                getIMInfo(userBean, mainPersonTokenBean);
            }

            @Override
            public void onError(String errMsg) {
                hideLoadingDialog();
                ToastUtils.showShort(errMsg);
            }
        });
    }

    /**
     * 获取环信账号信息
     *
     * @param userBean
     */
    private void getIMInfo(UserBean userBean, MainPersonTokenBean mainPersonTokenBean) {
        //注册环信账号
        mPresenter.getSaveImUser(mainPersonTokenBean.getNickName(), new ApiModel.CommonCallback<MainPersonalImNumber>() {
            @Override
            public void onSuccess(MainPersonalImNumber mainPersonalImNumber) {
                //登录环信
                Hawk.put(SPKey.SP_KEY_USER_IM_CHAT, mainPersonalImNumber);
                loginHx(userBean, mainPersonalImNumber);
            }

            @Override
            public void onError(String errMsg) {
                hideLoadingDialog();
                ToastUtils.showShort(errMsg);
            }
        });
    }

    /**
     * 登录环信
     *
     * @param userBean
     * @param mainPersonalImNumber
     */
    private void loginHx(UserBean userBean, MainPersonalImNumber mainPersonalImNumber) {
        EMClient.getInstance().login(mainPersonalImNumber.getUserName(), mainPersonalImNumber.getPassword(), new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                hideLoadingDialog();
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                startMainActivity(userBean);
            }

            @Override
            public void onProgress(int progress, String status) {
                ToastUtils.showShort(status);
            }

            @Override
            public void onError(int code, final String message) {
                hideLoadingDialog();
                if (200 == code) {
                    //已经登录
                    startMainActivity(userBean);
                    return;
                }
                ToastUtils.showShort(message + "(" + code + ")");
            }
        });
    }

    /**
     * 跳转绑定手机号码
     *
     * @param userBean
     */
    private void startBindPhoneActivity(UserBean userBean) {
        Intent intent = new Intent(RegisterActivity.this, BindPhoneActivity.class);
        intent.putExtra("data", JSON.toJSONString(userBean));
        startActivity(intent);
        finish();
    }

    /**
     * 登录成功 跳转主页
     *
     * @param userBean
     */
    private void startMainActivity(UserBean userBean) {
        Hawk.delete(SPKey.SP_KEY_USER_MY_INFO);
        Hawk.put(SPKey.SP_KEY_USER_INFO, userBean);
        handler.postDelayed(() -> {
            if (getIntent().getBooleanExtra("intentMain", true)) {
                //是否需要跳转主页
                Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                startActivity(intent);
            }
            finish();
        }, 50);
    }

    @Override
    public void onLoginFailed(String error) {
        hideLoadingDialog();
        ToastUtils.showShort(error);
    }

    @Override
    public void onVerifyCodeSuccess(String info) {
        hideLoadingDialog();
        ToastUtils.showShort("验证码已发送到你手机");
        timer();
    }

    private void stopTimer() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    private void timer() {
        stopTimer();
        codeTextView.setEnabled(false);
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long l) {
                codeTextView.setText((l / 1000) + "s");
            }

            @Override
            public void onFinish() {
                codeTextView.setText("获取验证码");
                codeTextView.setEnabled(true);
            }
        };
        countDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    @Override
    public void onVerifyCodeFailed(String error) {
        hideLoadingDialog();
        ToastUtils.showShort(error);
    }

    @Override
    public void onRegisterSuccess(String userBean) {
        hideLoadingDialog();
//        ToastUtils.showShort("注册成功");
//        Intent intent = new Intent(mActivity, LoginActivity.class);
//        intent.putExtra("account", accountEditText.getText().toString());
//        intent.putExtra("pwd", passwordEditText.getText().toString());
//        startActivity(intent);
//        finish();

        //登录
        login();
    }

    private void login() {
        showLoadingDialog(false);
        mPresenter.login(accountEditText.getText().toString(), passwordEditText.getText().toString());
    }

    @Override
    public void onRegisterFailed(String error) {
        hideLoadingDialog();
        ToastUtils.showShort(error);
    }

    @Override
    public void onBindPhoneSuccess(String userBean) {

    }

    @Override
    public void onBindPhoneFailed(String error) {

    }

}
